package com.hs.netty.chapter04;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author: songhao
 * @Date: 2021/8/25
 * @Description: TODO
 */
public class SimpleChatClient2 {

    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8888;
        System.out.println("连接 => " + host + ",端口号:" + port);

        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new SimpleChatClientInitalizer());

            //启动客户端
            Channel channel = bootstrap.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while(true){
                channel.writeAndFlush(in.readLine() + "\r\n");
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            workGroup.shutdownGracefully();
        }
    }
}
